//
// Created by 21126 on 2023/5/30.
//
#include "U2_S4.h"
#include <opencv2/face.hpp>

/**
 * 开启摄像头
 * @return 成功开启返回0，否则返回-1
 */
int openCapture()
{
    cv::VideoCapture capture(0);
    if (!capture.isOpened())
    {
        std::cout<<"fail open capture"<<std::endl;
        return -1;
    }

    return 0;
}

/**
 * 关闭摄像头和窗口
 * @param capture 要关闭的摄像头
 */
void closeCapture(cv::VideoCapture capture)
{
    capture.release();
    cv::destroyAllWindows();
}

/**
 * 开启人脸识别
 * @param capture 摄像头设备
 */
void startCapture(cv::VideoCapture capture)
{
    cv::CascadeClassifier faceCascade;
    faceCascade.load("/usr/local/opencv/opencv-4.6.0/data/haarcascades/haarcascade_frontalface_default.xml");

    cv::Ptr<cv::face::LBPHFaceRecognizer> recognizer = cv::face::LBPHFaceRecognizer::create();
    recognizer->read("model_path");

    cv::Mat frame;
    while (true)
    {
        capture.read(frame);

        cv::Mat gray_pic;
        cv::cvtColor(frame, gray_pic, cv::COLOR_BGR2GRAY);

        std::vector<cv::Rect> faces;
        faceCascade.detectMultiScale(gray_pic, faces, 1.1, 2, 0, cv::Size(30, 30));

        for (const auto & face : faces)
        {
            cv::Mat faceROI = gray_pic(face);

            cv::resize(faceROI, faceROI, cv::Size(100, 100));

            int label;
            double conf;
            recognizer->predict(faceROI, label, conf);

            std::string result = "Unknown";
            if (conf > 70)
            {
                result = "Person" + std::to_string(label);
            }

            cv::rectangle(frame, face, cv::Scalar(0, 255, 0), 2);
            cv::putText(frame, result, cv::Point(face.x, face.y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.9, cv::Scalar(0, 255, 0), 2);
        }

        cv::imshow("Face Recognition", frame);

        if (cv::waitKey(1) == 27)
            break;
    }
}